package com.stylefeng.guns.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import me.hao0.wechat.core.Wechat;
import me.hao0.wechat.core.WechatBuilder;
import me.hao0.wepay.core.Wepay;
import me.hao0.wepay.core.WepayBuilder;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: xuzhou
 * Date: 2018/6/7 上午1:51
 * Description:
 */
public class WechatUtils {

    private static Wechat wechatkyy;
    private static Wechat wechat;

    private static Wepay wepay;


    private WechatUtils() {
        wechat = WechatBuilder.newBuilder("wxadaeb684d0d10864","f4cf2e18b430c2533ddeb88183b382b3").build();

        wechatkyy = WechatBuilder.newBuilder("wx60b38061bc361bec","40d381cb9917db082580618d766243bf").build();

        wepay = WepayBuilder.newBuilder("wxadaeb684d0d10864", "7C99F0E3D2DF03519D3449A7A33A8D28", "1511735201").build();
    }

    public static String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    public static void encodeOutPutSteam(OutputStream outputStream, String contents, BarcodeFormat barcodeFormat, Integer margin, ErrorCorrectionLevel errorLevel, String format, int width, int height) {
        Map<EncodeHintType, Object> hints = new HashMap();
        hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
        hints.put(EncodeHintType.MARGIN, margin);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        try {
            BitMatrix bitMatrix = (new MultiFormatWriter()).encode(contents, barcodeFormat, width, height, hints);
            MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
        } catch (Exception var13) {
            var13.printStackTrace();
        } finally {
            IOUtils.closeQuietly(outputStream);
        }

    }

    private static final WechatUtils single = new WechatUtils();

    public static WechatUtils getInstance() {
        return single;
    }

    public Wechat getWechat() {
        return wechat;
    }

    public Wepay getWepay() {
        return wepay;
    }

    public Wechat getWechatkyy() {
        return wechatkyy;
    }
}
